package com.utils;

import android.app.Activity;
import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;


import com.utils.http.DJLOKHttpClient;
import com.utils.http.HttpResponseHandler;
import com.utils.interfaces.SelectTypeUtils;
import com.utils.interfaces.SelectUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 网络请求
 * Created by tcj on 2018/7/6 0006.
 */

public class MyHttpUtils {
    //保存的文件 采用隐藏文件的形式进行保存
    private static final String DEVICES_FILE_NAME = "DJLMESSAGE.DEVICES";
    //保存文件的路径
    private static final String CACHE_IMAGE_DIR = "/DaoJiaLe/B6";
    /**
     * 获取所有筛选条件
     */
    public static void getAllFiltrate(Activity activity,String url, final SelectUtils selectUtils) {
        Map<String, String> map = new HashMap<>();
        map.put("select_city", AppConfig.getInstance().getCityId());
        DJLOKHttpClient.asyncGet(url, new HttpResponseHandler() {
            @Override
            public void onSuccess(JSONObject response) {
                try {
                    int code = response.getInt("status");
                    if (code == 200) {
                        String data = response.getString("data");
                        AppConfig.getInstance().setAllFiltrate(data);
                        selectUtils.getData("");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onProgress(int progress) {

            }

            @Override
            public void onError(int state, String error) {

            }
        }, map, activity);
    }

    /**
     * 追加token请求参数
     *
     * @param paramJson
     * @return
     */
    public static Map<String, String> setToken(Map<String, String> paramJson) {
        if (!TextUtils.isEmpty(AppConfig.getInstance().getToken())) {
            paramJson.put("jjrtoken", AppConfig.getInstance().getToken());
        }
        return paramJson;
    }


    /**
     * 验证登录状态
     *
     * @param context
     * @param respons
     */
    public static void setVerificationLogin(Context context, JSONObject respons) {
        try {
            int code = respons.getInt("status");
            String msg = respons.getString("msg");
            switch (code) {
                case 400:
                    //账号在其他设备登录
//                    UserUtils.getInstance().isAnewLogin((Activity) context, msg);
//                    UserUtils.getInstance().outLogin(context);
                    break;
                case 401:
                    //账号在其他设备登录
//                    UserUtils.getInstance(context).outLogin();
//                    //更新用户信息
//                    EventEntity eventEntity = new EventEntity(EventEntity.REFRES_USER_INFO);
//                    EventBus.getDefault().post(eventEntity);
//                    UserUtils.getInstance(context).isAnewLogin(msg);
                    break;
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 验证登录状态
     *
     * @param respons
     */
    public static void setVerificationLogin(JSONObject respons, SelectTypeUtils utils) {
        try {
            int code = respons.getInt("status");
            String msg = respons.getString("msg");
            switch (code) {
                case 400:
                    //账号在其他设备登录
                    utils.getData(msg, code);
//                    UserUtils.getInstance().isAnewLogin((Activity) context, msg);
//                    UserUtils.getInstance().outLogin(context);
                    break;
                case 401:
                    utils.getData(msg, code);
                    //账号在其他设备登录
//                    UserUtils.getInstance(context).outLogin();
//                    //更新用户信息
//                    EventEntity eventEntity = new EventEntity(EventEntity.REFRES_USER_INFO);
//                    EventBus.getDefault().post(eventEntity);
//                    UserUtils.getInstance(context).isAnewLogin(msg);
                    break;
            }

        } catch (JSONException e) {
        }
    }

    /**
     * 获取连接后缀
     *
     * @param url
     * @return
     */
    public static String getParseSuffix(String url) {
        Pattern pattern = Pattern.compile("\\S*[?]\\S*");
        Matcher matcher = pattern.matcher(url);
        String[] spUrl = url.toString().split("/");
        int len = spUrl.length;
        String endUrl = spUrl[len - 1];

        if (matcher.find()) {
            String[] spEndUrl = endUrl.split("\\?");
            return spEndUrl[0].split("\\.")[1];
        }
        return endUrl.split("\\.")[1];
    }

    /**
     * 获取融云状态判断登陆是否成功
     *
     * @return
     */
    public static boolean detectionRongIMLoginState(Activity activity) {
        //获取融云状态判断登陆是否成功
        int imLoginState = AppConfig.getInstance().getIMLoginState();
        if (imLoginState != 0) {
//            SysAlertDialog.showAlertDialog(activity, "提示",
//                    "微聊登陆异常，无法发送微聊消息，建议退出后重新登陆。", "重新登陆",
//                    (dialog, which) -> {
//                        //退出登录 回到登录界面
//                        UserUtils.getInstance(activity).outLogin();
//                        EventEntity eventEntity = new EventEntity(EventEntity.REFRES_USER_INFO);
//                        EventBus.getDefault().post(eventEntity);
//                        EventEntity outLogin = new EventEntity(EventEntity.REFRES_OUT_LOGIN);
//                        EventBus.getDefault().post(outLogin);
//                        UserUtils.getInstance(activity).userIsLogin();
//                    }, "取消", null);
            return false;
        }
        return true;
    }

    /**
     * 统一处理 保存的文件的地址
     *
     * @param context
     * @return
     */
    private static File getDevicesDir(Context context) {
        File mCropFile = null;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File cropdir = new File(Environment.getExternalStorageDirectory(), CACHE_IMAGE_DIR);
            if (!cropdir.exists()) {
                cropdir.mkdirs();
            }
            mCropFile = new File(cropdir, DEVICES_FILE_NAME); // 用当前时间给取得的图片命名
        } else {
            File cropdir = new File(context.getFilesDir(), CACHE_IMAGE_DIR);
            if (!cropdir.exists()) {
                cropdir.mkdirs();
            }
            mCropFile = new File(cropdir, DEVICES_FILE_NAME);
        }
        return mCropFile;
    }

    /**
     * 返回完整的图片路径
     *
     * @param url
     * @return
     */
    public static String getUrl(String url) {
        if (TextUtils.isEmpty(url)) {
            return "";
        }
        try {
            if (!url.contains("http://") && !url.contains("https://")) {
                url = AppConfig.getInstance().getmPrivateImageURL() + url;
            }
        } catch (Exception e) {
            return url;
        }
        return url;
    }

    /**
     * 公共图片服务器   （用户头像，新房评论图片，评论用户头像）
     * <p>
     * 用户头像
     * 新房海报
     * 专题图片
     * 经纪人故事
     * 小区故事
     * 新房点评上传
     *
     * @param url
     * @return
     */
    public static String getPublicUrl(String url) {
        if (TextUtils.isEmpty(url)) {
            return "";
        }
        try {
            if (!url.contains("http://") && !url.contains("https://")) {
                url = AppConfig.getInstance().getImageURL() + url;
            }
        } catch (Exception e) {
            return "";
        }
        return url;
    }

    /**
     * 返回完整的路径  (全景视频)
     *
     * @param url
     * @return
     */
    public static String getFullUrl(String url) {
        if (TextUtils.isEmpty(url)) {
            return "";
        }
        try {
            if (!url.contains("http://") && !url.contains("https://")) {
                //临时城市切换时加载图片地址
                url = AppConfig.getInstance().getmBucketDomain() + url;
            }
        } catch (Exception e) {
            return url;
        }
        return url;
    }

    /**
     * 返回POST请求 URL 添加城市CODE 字符串
     *
     * @return
     */
    public static String getUrlAddCityCode() {
        return "?select_city=" +  AppConfig.getInstance().getCityId();
    }

    /**
     * 返回GET请求 MAP追加参数 城市ID
     *
     * @param map
     * @return
     */
    public static Map<String, String> getMapAddCityCode(Map<String, String> map) {
        if (map == null) {
            map = new HashMap<String, String>();
        }
        map.put("select_city", AppConfig.getInstance().getCityId());
        return map;
    }

    /**
     * 返回GET请求 MAP追加参数 城市ID
     *
     * @return
     */
    public static void getAccessToken(String sccessTokenUrl,String requestUrl, HttpResponseHandler responseHandler, Map<String, String> map, Activity activity) {
        Map<String, String> stringStringMap = MyHttpUtils.setToken(new HashMap<>());
        DJLOKHttpClient.asyncPost(sccessTokenUrl, new HttpResponseHandler() {
            @Override
            public void onSuccess(JSONObject response) {
                try {
                    int code = response.getInt("status");
                    if (code == 200) {
                        String data = response.getString("data");
                        if(!TextUtils.isEmpty(data)){
                            map.put("accessToken", data);
                            DJLOKHttpClient.asyncPost(requestUrl,
                                    responseHandler, map, activity);
                        }else {
                            responseHandler.onError(101,"非法的网络请求");
                        }
                    }else {
                        responseHandler.onError(101,"非法的网络请求");
                    }
                } catch (Exception e) {
                    responseHandler.onError(101,"非法的网络请求");
                }

            }

            @Override
            public void onProgress(int progress) {

            }

            @Override
            public void onError(int state, String error) {
                responseHandler.onError(101,"非法的网络请求");
            }
        }, stringStringMap, activity);
    }
}
